/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.articles.importFromLn.cli;

import cz.mzk.kramerius.articles.importFromLn.reindexing.IssueUuidCollector;
import cz.mzk.kramerius.articles.importFromLn.reindexing.Reindexer;
import cz.mzk.kramerius.commons.PropertyLoader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan@mzk.cz)
 */
class ReindexIssuesWithArticlesAction implements Action {

    private static final Logger logger = Logger.getLogger(ReindexIssuesWithArticlesAction.class.getName());
    private final Set<String> uuidList;
    private final Reindexer reindexer;
    private final int secondsToWait;

    ReindexIssuesWithArticlesAction(PropertyLoader properties, File dirListFile, int secondsToWait) throws IOException {
        List<File> dirList = loadDirList(dirListFile);
        IssueUuidCollector issueCollector = new IssueUuidCollector(dirList);
        uuidList = issueCollector.getIssueUuids();
        logger.log(Level.INFO, "Issues to reindex: {0}", uuidList.size());
        reindexer = new Reindexer(properties);
        this.secondsToWait = secondsToWait;
    }

    private List<File> loadDirList(File dirListFile) throws IOException {
        List<File> result = new ArrayList<File>();
        LineNumberReader reader = new LineNumberReader(new FileReader(dirListFile));
        while (reader.ready()) {
            String filename = reader.readLine();
            result.add(new File(filename));
        }
        return result;
    }

    @Override
    public void run() {
        int counter = 0;
        for (String uuid : uuidList) {
            try {
                logger.log(Level.INFO, "{0}:{1}", new Object[]{counter++, uuidList.size()});
                reindexer.reindex(uuid);
                busyWait(secondsToWait);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "couldn't perform reindexing", e);
            }
        }
    }

    private void busyWait(int secondsToWait) {
        long start, end;
        start = System.currentTimeMillis();
        do {
            end = System.currentTimeMillis();
        } while ((end - start) < (secondsToWait * 1000));
    }
}
